<?php
declare (strict_types=1);

namespace app\middleware;

use app\model\ApiLogDao;
use think\Response;

class ApiLog
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $url = $request->url();
        if (str_starts_with($url, '/admin') || !env("APP_DEBUG",false)) {//不记录后台信息
            return $next($request);
        }
        $start = microtime(true);
        $info = new  ApiLogDao;
        if ($request->has('uid')) {
            $info->uid = $request->param('uid');
        }
        $info->url = $url;
        $info->ip = $request->ip();
        $params= $request->param();
        if (!empty($params)) {
            $info->request = $params;
        } elseif ($request->getContent() !="") {
            $info->request = $request->getContent();
        }
        $info->header = $request->header();
        $info->method = $request->method();
        $info->save();
        $response = $next($request);
        $end = microtime(true);

        $info->response = $response->getData();
        $info->code = $response->getCode();
        $info->time = round($end - $start, 6) * 1000;
        $info->uid= $request->uid;
        $info->save();
        return $response;
    }
}
